<template>
  <div class="user-management">
    <div class="page-header">
      <h2>用户管理</h2>
      <el-button type="primary" @click="showCreateDialog">
        <el-icon><Plus /></el-icon>
        新建用户
      </el-button>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.userName"
            placeholder="请输入用户名"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input
            v-model="searchForm.email"
            placeholder="请输入邮箱"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 用户表格 -->
    <el-card shadow="never">
      <el-table
        v-loading="userStore.loading"
        :data="userStore.users"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="userName" label="用户名" width="120" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column label="角色" width="200">
          <template #default="{ row }">
            <el-tag
              v-if="row.roles && row.roles.length > 0"
              size="small"
              type="primary"
            >
              {{ row.roles[0].name }}
            </el-tag>
            <span v-else class="text-gray">未分配角色</span>
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt || row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="small" @click="showEditDialog(row)">
                编辑
              </el-button>
              <el-button size="small" type="warning" @click="showAssignRoleDialog(row)">
                分配角色
              </el-button>
              <el-button size="small" type="info" @click="showChangePasswordDialog(row)">
                修改密码
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="userStore.currentPage"
          v-model:page-size="userStore.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="userStore.total"
          layout="total, sizes, prev, pager, next, jumper"
          :prev-text="'上一页'"
          :next-text="'下一页'"
          :page-size-text="'条/页'"
          :total-text="'共 {total} 条'"
          :jumper-text="'前往'"
          :page-text="'页'"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 创建/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑用户' : '新建用户'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="确认密码" prop="confirmPassword">
          <el-input
            v-model="userForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>

      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 分配角色对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      title="分配角色"
      width="500px"
    >
      <div class="role-assignment">
        <p>为用户 <strong>{{ currentUser?.email }}</strong> 分配角色：</p>
        <el-radio-group v-model="selectedRole">
          <el-radio
            v-for="role in userStore.roles"
            :key="role.id"
            :value="role.id"
            :label="role.id"
          >
            {{ role.name }}
          </el-radio>
        </el-radio-group>
      </div>
      
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="assignLoading" @click="handleAssignRole">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="500px"
      @close="resetPasswordForm"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <div class="password-change">
          <p>为用户 <strong>{{ currentUser?.email }}</strong> 修改密码：</p>
          <el-form-item label="原密码" prop="oldPassword">
            <el-input
              v-model="passwordForm.oldPassword"
              type="password"
              placeholder="请输入原密码"
              show-password
            />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码"
              show-password
            />
          </el-form-item>
        </div>
      </el-form>
      
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="passwordLoading" @click="handleChangePassword">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  Refresh
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const userFormRef = ref()
const passwordFormRef = ref()
const dialogVisible = ref(false)
const roleDialogVisible = ref(false)
const passwordDialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const assignLoading = ref(false)
const passwordLoading = ref(false)
const currentUser = ref(null)
const selectedRole = ref('')

// 搜索表单
const searchForm = reactive({
  userName: '',
  email: ''
})

// 用户表单
const userForm = reactive({
  id: '',
  userName: '',
  email: '',
  password: '',
  confirmPassword: ''
})

// 确认密码验证函数
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== userForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

// 表单验证规则
const userRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 密码修改表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: ''
})

// 密码修改验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 搜索
const handleSearch = () => {
  userStore.setPage(1)
  userStore.fetchUsers(searchForm)
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    userName: '',
    email: ''
  })
  handleSearch()
}

// 显示创建对话框
const showCreateDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (user) => {
  isEdit.value = true
  Object.assign(userForm, {
    id: user.id,
    userName: user.userName,
    email: user.email
  })
  dialogVisible.value = true
}

// 显示分配角色对话框
const showAssignRoleDialog = (user) => {
  currentUser.value = user
  selectedRole.value = user.roles && user.roles.length > 0 ? user.roles[0].id : ''
  roleDialogVisible.value = true
}

// 显示修改密码对话框
const showChangePasswordDialog = (user) => {
  currentUser.value = user
  passwordDialogVisible.value = true
}

// 重置密码表单
const resetPasswordForm = () => {
  Object.assign(passwordForm, {
    oldPassword: '',
    newPassword: ''
  })
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(userForm, {
    id: '',
    userName: '',
    email: '',
    password: '',
    confirmPassword: ''
  })
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    submitLoading.value = true
    
    if (isEdit.value) {
      await userStore.updateUser(userForm.id, userForm)
      ElMessage.success('用户更新成功')
    } else {
      await userStore.createUser(userForm)
      ElMessage.success('用户创建成功')
    }
    
    dialogVisible.value = false
    resetForm()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 分配角色
const handleAssignRole = async () => {
  if (!selectedRole.value) {
    ElMessage.warning('请选择一个角色')
    return
  }
  
  try {
    assignLoading.value = true
    await userStore.assignUserRole(currentUser.value.id, [selectedRole.value])
    ElMessage.success('角色分配成功')
    roleDialogVisible.value = false
  } catch (error) {
    console.error('角色分配失败:', error)
  } finally {
    assignLoading.value = false
  }
}

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true
    
    const passwordData = {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    }
    
    await userStore.changePassword(currentUser.value.id, passwordData)
    ElMessage.success('密码修改成功')
    passwordDialogVisible.value = false
    resetPasswordForm()
  } catch (error) {
    console.error('密码修改失败:', error)
    ElMessage.error('密码修改失败，请检查原密码是否正确')
  } finally {
    passwordLoading.value = false
  }
}

// 删除用户
const handleDelete = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.email}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await userStore.deleteUser(user.id)
    ElMessage.success('用户删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

// 分页处理
const handleSizeChange = (size) => {
  userStore.setPageSize(size)
  userStore.fetchUsers(searchForm)
}

const handleCurrentChange = (page) => {
  userStore.setPage(page)
  userStore.fetchUsers(searchForm)
}

onMounted(async () => {
  await userStore.fetchUsers()
  await userStore.fetchRoles()
})
</script>

<style scoped>
.user-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.search-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.text-gray {
  color: #999;
  font-size: 12px;
}

.role-assignment {
  padding: 10px 0;
}

.role-assignment p {
  margin-bottom: 15px;
  color: #666;
}

.password-change {
  padding: 10px 0;
}

.password-change p {
  margin-bottom: 15px;
  color: #666;
}

:deep(.el-radio-group) {
  display: flex;
  flex-direction: column;
  gap: 10px;
  align-items: flex-start;
}

:deep(.el-radio) {
  margin-right: 0;
  margin-bottom: 0;
  align-items: center;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}
查询人脸分组中的人脸信息
.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
}

.action-buttons .el-button {
  margin: 0;
  min-width: 60px;
}
</style>